package cn.momoky.ccool.controller;

import cn.momoky.ccool.pojo.FileNode;
import cn.momoky.ccool.service.FileNodeService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/fn")
@AllArgsConstructor
public class FileNodeController {

    private final FileNodeService fileNodeService;


    @PostMapping("/mkdir")
    public FileNode mkdir(@RequestBody FileNode FileNode) {
        return fileNodeService.mkdir(FileNode);
    }

    @PostMapping("/new-file-tree/{parentId}")
    public Map<String, Long> newFileTree(@PathVariable("parentId") Long parentId,
                                         @RequestBody List<FileNode> nodeList) {
        fileNodeService.newFileTree(parentId, nodeList);
        Map<String, Long> map = new HashMap<>();
        nodeList.forEach(node -> {
            map.put(node.getPath(), node.getParentId());
        });
        return map;
    }


    @GetMapping
    public FileNode getFileNodeByPath(@RequestParam("path") String path) {
        FileNode fileNode;
        if (path.length() == 0) {
            fileNode = fileNodeService.getRoot();
        } else {
            fileNode = fileNodeService.findByPath(path);
        }

        if (fileNode == null) return null;

        fileNode.setChildren(fileNodeService.findByParentId(fileNode.getId()));
        return fileNode;
    }

    @GetMapping("/list/{parentId}")
    public List<FileNode> list(@PathVariable("parentId") Long parentId) {
        return fileNodeService.findByParentId(parentId);
    }


    @DeleteMapping("/del-node/{id}")
    public void remove(@PathVariable("id") Long id) {
        fileNodeService.removeNode(id);
    }

    @PostMapping("/del-node")
    public void remove(@RequestBody List<Long> ids) {
        fileNodeService.removeNode(ids);
    }
}
